package Twitim::Config;

use strict;
use warnings;

my $config_file;

sub new {
    my $this = shift;
    $config_file = shift;
    my $class = ref($this) || $this;
    my $self = {@_};
    bless $self, $class;

    return $self;
}

sub read {
    my $self = shift;
    _check_permission($config_file);

    open my $fh, '<:utf8', $config_file or return 0;

    my $block;
    while ( my $line = <$fh> ) {
        next if ( $line =~ /(^[;#]|^\s*$)/ );

        if ( $line =~ /^\s*\[(.*)\]\s*$/ ) {
            $block = $1;
        }
        elsif ( $line =~ /^\s*(.*?)\s*=\s*(.*)\s*$/ ) {
            $self->{$block}->{$1} = $2;

            #print "$block: $1 / $2\n";
        }

        #print $line;
    }
    close $fh;

    return $self;
}

sub write {
    my $self = shift;

    open my $fh, '>:utf8', $config_file or return 0;

    foreach my $block ( sort keys %{$self} ) {
        print {$fh} "[$block]\n";

        foreach my $key ( sort keys %{ $self->{$block} } ) {
            print {$fh} "$key = $self->{$block}->{$key}\n";
        }
        print {$fh} "\n";
    }
    close $fh;
}

sub _check_permission {
    my $file = shift;

    ( my $mode ) = ( stat($file) )[2];
    $mode = sprintf( "%o", $mode );
    $mode = substr( $mode, 3, 3 );
    chmod oct(600), $file if ( $mode ne "600" );
}

1;
